package c.main.core;

import c.main.util.ClassUtils;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Author: chengwei
 * Date:   2016/3/16
 * Time:   9:57
 */
public class BeanLoader extends Loader{
    public void load (WcsProperties wcsProperties) {
        String packages = wcsProperties.getImpl_package();
        String[] packageSet = packages.split(",");
        Set<Class<?>> set = new HashSet<>();
        for (String pag : packageSet) {
            set.addAll(ClassUtils.getClasses(pag));
        }
        Object o;
        for (Class<?> clazz : set) {

            if (clazz.isInterface()) {
                for (Class<?> clazz2 : set) {
                    if (!clazz2.isInterface() && clazz.isAssignableFrom(clazz2)) {
                        try {
                            o = clazz2.newInstance();
                            C.addBean(clazz.getName(), o);
                            log.info(String.format("名称为%s的Bean加载完成..", clazz.getName()));
                        } catch (ReflectiveOperationException e) {
                            e.printStackTrace();
                            log.info(String.format("名称为%s的Bean加载失败...", clazz.getName()));
                        }
                    }
                }
            }

        }
        
        //属性注入
        WcsResource wcsResource;
        Map<String,Object> beanMap = C.getInstance().getContext().getBeanMap();
        Set<String> keySet = beanMap.keySet();
        for (String key : keySet) {
            Class<?> clazz = beanMap.get(key).getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                wcsResource = field.getAnnotation(WcsResource.class);
                if (wcsResource != null) {
                    try {
                        o = C.getBean(field.getType());
                        field.setAccessible(true);
                        field.set(C.getBean(key),o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
